<?php
namespace Platform\Domain;

use Platform\Model\Admin as AdminModel;
use Platform\Model\AdminToken as AdminTokenModel;
use Platform\Model\SystemMenu as MenuModel;
use Platform\Model\SystemMenuRole as SystemMenuRoleModel;
use PhalApi\Exception\BadRequestException;

class Login{

    const ADMIN_STATE_NORMAL = 1;
    const ADMIN_STATE_BANNED = 0;

    //登录
    public function login($username, $password) {
        $model = new AdminModel();
        $tokenModel = new AdminTokenModel();
        $admin = $model->getByUsername($username);
        if (empty($admin)) {
            throw new BadRequestException('用户名不存在！');
        }
        if ($admin['state'] != self::ADMIN_STATE_NORMAL) {
            throw new BadRequestException('用户已被禁用！');
        }
        if ($admin['delete_flag']=='Y') {
            throw new BadRequestException('用户已被删除！');
        }
        $encryptPass = $this->encryptPassword($password, $admin['salt']);
        if ($encryptPass != $admin['password']) {
            throw new BadRequestException('密码错误！');
        }
        //创建当前的登录token
        $token = $this->encryptPassword($admin['id'].time().$password, $admin['salt']);
        //根据当前user_id判断表里是否存在，存在更新，不存在新增
        $tokenData = $tokenModel->getData(array('user_id'=>$admin['id']));
        if( empty( $tokenData ) ){
            //存入对应表中
            $data = array();
            $data['user_id'] = $admin['id'];
            $data['token'] = $token;
            $data['add_time'] = time();
            $data['invalid_time'] = time()+60*60*24;
            $tokenModel->insert($data);
        }else{
            //更新
            $data = array();
            $data['token'] = $token;
            $data['add_time'] = time();
            $data['invalid_time'] = time()+60*60*24;
            $tokenModel->updateAll(array('user_id'=>$admin['id']),$data);
        }
        $outData = $admin;
        $outData['token'] = $token;
        // 开启会话
//        \PhalApi\DI()->manage->login($token);
        return $outData;
    }
    //加密密码
    public function encryptPassword($password, $salt) {
        return md5(md5(sha1($password . $salt)));
    }
    //获取所有菜单
    public function listAllMenus() {
        $model = new MenuModel();
        $SystemMenuRoleModel = new SystemMenuRoleModel();
        $menus = $model->listAllMenus();
        //循环菜单查询菜单和角色的关联关系
        foreach ( $menus as $k => $v ){
            $roles = $SystemMenuRoleModel->getList(array('menu_id'=>$v['id']));
            if( !empty( $roles ) ){
                $role_ids = array();
                foreach ( $roles as $kk => $vv ){
                    $role_ids[$kk] = (string)$vv['role_id'];
                }
                $menus[$k]['roles'] = $role_ids;
            }else{
                $menus[$k]['roles'] = array();
            }
        }
        //根据parentId分子类
        $menus = $this->_getTree($menus);
        return $menus;
    }

    //树方法
    private function _getTree($data)
    {
        //第一步初始化数据
        $items = array();
        foreach($data as $value){
            $items[$value['authorityId']] = $value;
        }
        //第二部 遍历数据 生成树状结构
        $tree = array();
        foreach($items as $key => $item){
            if(isset($items[$item['parentId']])){
                $items[$item['parentId']]['children'][] = &$items[$key];
            }else{
                $tree[] = &$items[$key];
            }
        }
        return $tree;
    }
}
